<template>
  <div class="tag-container">
    <div class="bg-white">
      <div class="mx-auto max-w-11xl pt-5 pb-5 px-4 lg:px-4">
        <div class="breadcrumbs space-x-2 text-base mx-auto flex flex-wrap items-center">
          <common-link path="/"
            class="text-gray-1000 hover:text-purple-1200 go-home">
            {{$t('home')}}
          </common-link>
          <svg-icon className="text-gray-1800 text-mini text-slate-400 mx-3"
            iconName='right_outlined'></svg-icon>
          <common-link path="/"
            class="text-gray-1000 hover:text-purple-1200 go-home">
            {{$t('tag_tag')}}
          </common-link>
          <svg-icon className="text-gray-1800 text-mini text-slate-400 mx-3"
            iconName='right_outlined'></svg-icon>
          <span class="text-gray-1400 text-base">
            {{tag}}
          </span>
        </div>
        <div class="pt-7 sm:pt-7">
          <h1 class="text-lg sm:text-4xl text-gray-1000"
            v-html="$t('tag_title_discoverBest', {tagName: tag})"></h1>
          <min-share class="mt-4 sm:mt-7"></min-share>
          <div class="text-gray-1000 text-lg leading-7 mt-5">
            <p v-html="$t('tag_page_desc01', {tagName: tag})"></p>
            <p v-html="$t('tag_page_desc02', {tagName: tag, toolsNum: topToolsList.length, toolsList: getNameTextVal(topToolsList) })"></p>
          </div>
          <sponsored-by class="mt-3 text-lg text-gray-1000 font-semibold"></sponsored-by>
        </div>
      </div>
    </div>
    <div class="max-w-11xl mx-auto px-4 py-7">
      <div class="xl:grid xl:grid-cols-5 xl:gap-5 items-start">
        <div class="xl:col-span-4"
          :class="{'xl:col-span-5': !(recommendToolsList && recommendToolsList.length > 0)}">
          <div class="md:flex items-center justify-between flex-wrap md:flex-nowrap gap-4">
            <div class="sm:flex items-center justify-between bg-white border rounded-lg px-5 py-2 sm:py-3 max-w-full text-base text-gray-1500 sm:flex-nowrap gap-x-7 gap-y-4">
              <div>{{$t('tag_numberOfAls')}}<em class="text-lg text-gray-1000 font-semibold mr-7 not-italic">{{toolsList.length}}</em></div>
              <div class="mt-2 sm:mt-0"
                v-if="today">{{$t('tag_updatedTime')}}<em class="text-lg text-gray-1000 font-semibold not-italic">{{$formattedDate(today,fI18n,locale)}}</em></div>
            </div>
            <div class="mt-4 w-full md:mt-0 md:w-auto">
              <common-square-sort :targetObj="sortOptions"
                :hasBorder="true"
                :sort="sort"
                selectType="sort"
                class="block md:inline-block"
                @toSearch="toSearch"></common-square-sort>
            </div>
          </div>
          <template v-if="!loading">
            <div class="tools grid gap-5 sm:grid-cols-2 md:grid-cols-3 xl:grid-cols-4 mt-3.5"
              v-if="toolsList && toolsList.length > 0"
              v-loading="loading">
              <min-tool v-for="(item, key) in toolsList"
                :key="item.handle+'-'+key"
                :toolPosIndex="key"
                :toolPosition="tag"
                :tag="tag"
                :isHideCategories="true"
                :toolsData="item"
                :lazyLoad="key < 4 ? false : true">
                <div class="flex items-start flex-wrap flex-shrink-0 mt-3.5 gap-x-3 gap-y-2.5 maxHeight2"
                  :class="{'pr-8': item.is_ad}"
                  slot="extra">
                  <span class="text-base text-gray-1000 bg-gray-2100 max-w-max truncate rounded t-label">#{{tag}}</span>
                </div>
              </min-tool>
            </div>
            <el-empty v-else
              :description="$t('tag_noData')"></el-empty>
          </template>
          <div class="w-2/4 mx-auto py-20 text-center"
            v-else>
            <el-button type="text"
              class="cursor-default">
              <img src="@/static/images/loading.png"
                class="loading"
                alt=""
                srcset="">
            </el-button>
          </div>
          <div class="mt-16"
            v-if="prevNextTags && prevNextTags.length > 0">
            <h2 class="text-4xl text-gray-1000">
              {{$t('tag_moreTags')}}
            </h2>
            <div class="grid gap-4 sm:grid-cols-2 mt-5 sm:mt-7">
              <common-link path="/tag/:handle"
                v-for="(item, key) in prevNextTags"
                :key="key"
                :params='{handle: item }'
                class="flex items-center border border-gray-2000 rounded bg-white px-4 py-4 text-base text-gray-1000 font-medium hover:text-purple-1300 hover:border-purple-1300">
                {{item}}
              </common-link>
            </div>
          </div>
        </div>
        <div class="hidden xl:block xl:col-span-1"
          v-if="recommendToolsList && recommendToolsList.length > 0">
          <h3 class="text-34 text-gray-34 font-bold">{{$t('category_featured')}}</h3>
          <div class="tools space-y-4 mt-7 px-3.5 py-4 bg-white rounded-lg">
            <template v-for="(item, key) in recommendToolsList">
              <min-tool-featured :key="item.handle+'-'+key"
                v-if="key< 20"
                :toolPosIndex="key"
                :toolsData="item"></min-tool-featured>
            </template>
          </div>
        </div>
      </div>
    </div>
  </div>
  </div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  name: 'Tag',
  head() {
    return {
      htmlAttrs: {
        lang: this.locale,
      },
      title: this.title,
      meta: [
        {
          hid: 'description',
          name: 'description',
          content: this.description,
        },
        {
          hid: 'og:title',
          name: 'og:title',
          content: this.title,
        },
        {
          hid: 'og:description',
          name: 'og:description',
          content: this.description,
        },
        {
          hid: 'og:url',
          name: 'og:url',
          content: this.canonicalLink,
        },
        {
          hid: 'og:image:alt',
          name: 'og:image:alt',
          content: this.title,
        },
      ],
      link: [
        {
          rel: 'canonical',
          href: this.canonicalLink,
        },
      ],
    }
  },
  async asyncData({ app, route, params, query, $axiosApi, error, store }) {
    let date = new Date()
    let fullYear = date.getFullYear()
    const today = parseInt(Date.now()) / 1000
    try {
      const tag = params.handle
      let toolsList = []
      let topToolsList = []
      let prevNextTags = []
      let [toolsRes, recommendRes] = await Promise.all([
        $axiosApi.getTag({
          tag: encodeURIComponent(tag),
          order_by: 'id',
          direction: 'desc',
        }),
        $axiosApi.searchGetAd(),
        /* $axiosApi.getTools({
          page: 1,
          per_page: 100,
          history_has_recommended: 1,
        }), */
      ])

      let description, title

      if (toolsRes.code === 200) {
        prevNextTags = toolsRes.data.next_and_last_tags_name
        toolsList = toolsRes.data.data
        if (toolsList && toolsList.length > 10) {
          topToolsList = toolsList.slice(0, 10)
        } else {
          topToolsList = toolsList
        }
        title = app.i18n.t('tag_page_title', { tagName: tag })
        if (topToolsList && topToolsList.length > 0) {
          let toolListText = ''

          function websiteName(tool) {
            let toolName = tool.name
            if (tool.website && tool.website && tool.website.name) {
              toolName = tool.website.name
            }
            return toolName
          }

          topToolsList.forEach((item) => {
            toolListText = `${toolListText}${
              toolListText ? ', ' : ''
            }${websiteName(item)}`
          })
          description = app.i18n.t('tag_page_desc', {
            year: fullYear,
            tagName: tag,
            toolsList: toolListText,
          })
        } else {
          description = app.i18n.t('tag_page_desc', {
            year: fullYear,
            tagName: tag,
            toolsLis: 'Null',
          })
        }
      } else {
        title = app.i18n.t('common_title')
        description = app.i18n.t('common_desc')

        if (toolsRes && toolsRes.code && toolsRes.code === 404) {
          error({ statusCode: 404 })
        } else if (!(toolsRes && toolsRes.code && toolsRes.code === 401)) {
          error({
            message:
              'There is a problem with the network. Please refresh and try again later',
            statusCode: toolsRes.code,
          })
        }
      }

      let recommendToolsList = []
      if (recommendRes.code === 200) {
        if (
          recommendRes.data.featured_list &&
          recommendRes.data.featured_list.length > 0
        ) {
          store.commit(
            'SET_TOP_ADVERTISER',
            JSON.parse(JSON.stringify(recommendRes.data.featured_list[0]))
          )
          let firstAd = recommendRes.data.featured_list.shift()
          let rIndex = topToolsList.findIndex((item) => {
            return item.handle === firstAd.handle
          })
          if (rIndex !== -1) {
            topToolsList.splice(rIndex, 1)
          }
          topToolsList.unshift(firstAd)
        } else {
          store.commit('SET_TOP_ADVERTISER', null)
        }
        recommendToolsList =
          recommendRes.data.featured_list &&
          recommendRes.data.featured_list.length > 0
            ? recommendRes.data.featured_list
            : []
      } else {
        store.commit('SET_TOP_ADVERTISER', null)
      }

      /* if (recommendRes.code === 200) {
        recommendToolsList =
          oldRes.data.data && oldRes.data.data.length > 0
            ? oldRes.data.data
            : []
      } */

      return {
        toolsList,
        prevNextTags,
        topToolsList,
        tag,
        today,
        title,
        description,
        recommendToolsList,
      }
    } catch (err) {
      console.log(err)
    }
  },
  watch: {
    $route: {
      handler(route) {
        if (route.name === this.$route.name) {
          this.getTagsDetail()
        }
      },
      deep: true,
    },
  },
  computed: {
    ...mapState({
      locale: (state) => state.locale,
    }),
  },
  data() {
    return {
      title: null,
      description: null,
      canonicalLink: `https://www.toolify.ai${this.$route.fullPath}`,

      toolsList: [],
      prevNextTags: [],
      topToolsList: [],
      today: null,
      tag: null,
      sort: 'id',
      loading: false,

      sortOptions: {
        isShowOptions: false,
        options: [
          { label: 'tag_sortDefault', val: 'id' },
          { label: 'tag_sortBest', val: 'month_visited_count' },
          { label: 'tag_sortMostSaved', val: 'collected_count' },
          { label: 'tag_sortNewest', val: 'created_at' },
        ],
      },

      recommendToolsList: [],
    }
  },
  methods: {
    async getTagsDetail() {
      this.loading = true
      try {
        const tag = this.$route.params.handle
        let toolsRes = await this.$axiosApi.getTag({
          tag: encodeURIComponent(tag),
          order_by: this.sort ? this.sort : 'id',
          direction: 'desc',
        })
        this.loading = false
        if (toolsRes.code === 200) {
          this.prevNextTags = toolsRes.data.next_and_last_tags_name
          this.toolsList = toolsRes.data.data
          if (this.toolsList && this.toolsList.length > 10) {
            this.topToolsList = this.toolsList.slice(0, 10)
          } else {
            this.topToolsList = this.toolsList
          }
        } else {
        }
        this.sortOptions.isShowOptions = false
      } catch (err) {
        this.loading = false
        console.log(err)
      }
    },
    toSearch(val) {
      this.sort = val
      this.getTagsDetail()
    },
    fI18n(arg) {
      const hasKey = this.$i18n.t(arg)
      if (hasKey) {
        const result = this.$i18n.t(arg)
        return result
      }
      return arg
    },
  },
}
</script>
<style lang='scss' scoped>
.tag-container {
  background: #f8f9fb;
  .bg-white-linear {
    background: linear-gradient(180deg, #ffffff 0%, #f8f9fb 100%);
  }
  .tools {
    position: relative;
    ::v-deep .el-loading-mask {
      border-radius: 8px;
      .el-loading-spinner {
        svg {
          margin: 0 auto;
        }
      }
    }

    .maxHeight2 {
      max-height: 30px;
    }
    ::v-deep .ad {
      bottom: 19px !important;
    }
  }
}
</style>
